<template>
  <div id="contentBox">
    <el-button type="primary" @click="handleAddPoster">新建海报</el-button>
    <el-table
      :data="tableData"
      style="width: 100%;margin-top:10px"
      border
      fit
      :header-cell-style="{background:g.mainColor}"
    >
      <el-table-column prop="date" label="预览图" align="center">
        <template>
          <span>
            <img
              src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3372371941,4012056760&fm=26&gp=0.jpg"
              class="table-row-img"
            >
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="使用位置" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <!-- 创建海报 -->
    <el-dialog
      :title="title"
      :visible.sync="posterDialog"
      width="500px"
      @close="$refs['form'].clearValidate()"
      @opened="$refs['form'].clearValidate()"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item ref="posters" label="海报上传" prop="posters">
          <el-upload
            action="#"
            list-type="picture-card"
            accept=".jpg, .jpeg, .png, .JPG, .JPEG"
            :http-request="handleAvatar"
            :before-upload="beforeAvatarUpload"
            :class="{hide:hideUpload}"
            :file-list="postersList"
          >
            <i slot="default" class="el-icon-plus" />
            <div slot="file">
              <img class="el-upload-list__item-thumbnail" :src="form.valueData.avatar">
              <span class="el-upload-list__item-actions">
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove">
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="使用位置" prop="location">
          <el-select v-model="form.location" placeholder="请选择使用位置">
            <el-option label="分销海报" value="shanghai" />
            <el-option label="线下海报" value="beijing" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="posterDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 图片裁剪 -->
    <el-dialog
      title="裁剪图片"
      :visible.sync="cropper.dialog"
      width="600px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <div style="width:400px;height:400px;text-align:center;">
        <VueCropper
          ref="cropper"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          :info="true"
          :full="option.full"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :original="option.original"
          :auto-crop="option.autoCrop"
          :fixed="option.fixed"
          :fixed-number="option.fixedNumber"
          :center-box="option.centerBox"
          :info-true="option.infoTrue"
          :fixed-box="option.fixedBox"
        />
      </div>
      <div slot="footer" class="dialog-footer footer">
        <!-- <el-button @click="cropper.dialog = false">取 消</el-button> -->
        <el-button type="primary" @click="confirmCropper">确定裁剪</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { VueCropper } from 'vue-cropper'
export default {
  name: 'PosterList',
  components: { Pagination, VueCropper },
  data() {
    return {
      rules: {
        posters: [{ required: true, message: '请上传海报', trigger: 'change' }],
        location: [
          { required: true, message: '请选择使用位置', trigger: 'change' }
        ]
      },
      listQuery: {
        currentPage: 1,
        pageSize: 10
      },
      tableData: [
        {
          date: '2016-05-02',
          name: '分销海报',
          address: '上海市普陀区金沙江路 1518 弄'
        },
        {
          date: '2016-05-04',
          name: '分销海报',
          address: '上海市普陀区金沙江路 1517 弄'
        },
        {
          date: '2016-05-01',
          name: '分销海报',
          address: '上海市普陀区金沙江路 1519 弄'
        },
        {
          date: '2016-05-03',
          name: '分销海报',
          address: '上海市普陀区金沙江路 1516 弄'
        }
      ],
      form: {
        location: '',
        pass: '',
        valueData: {
          avatar: '',
          phone: ''
        }
      },
      cropper: {
        dialog: false,
        // src:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592979325958&di=95cd2f2b6fc195bab6e89fe3fb3fe629&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201306%2F29%2F20130629033734_XuJ5V.jpeg",
        width: 400,
        height: 400,
        aspectRatio: 1,
        fileBlob: {}
      },
      // 裁剪组件的基础配置option
      option: {
        mode: 'cover', // 图片默认渲染方式
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'jpeg', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 400, // 默认生成截图框宽度
        autoCropHeight: 400, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [400, 400], // 截图框的宽高比例
        full: false, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: false // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      total: 10,
      posterDialog: false, // 海报模态框
      title: '新建海报',
      disabled: false,
      postersList: [], // 图片上传信息
      hideUpload: false
    }
  },
  methods: {
    // 切换分页
    getList() {},
    handleEdit(row) {
      this.posterDialog = true
      this.hideUpload = false
      this.title = '编辑海报'
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该海报, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新建海报
    handleAddPoster() {
      this.posterDialog = true
      this.form.location = ''
      this.title = '新建海报'
      this.hideUpload = false
      this.postersList = []
    },
    // 上传文件之前的钩子 若返回false或者Promise则停止上传
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // upload上传图片时触发
    handleAvatar(res, fileList) {
      console.log(res)
      this.cropper.dialog = true
      this.option.img = URL.createObjectURL(res.file)
    },
    handleRemove() {
      this.postersList = []
      this.hideUpload = false
    },
    // 确定裁剪后获取截图的blob数据
    confirmCropper() {
      this.$refs.cropper.getCropBlob((data) => {
        const raw = {
          raw: data,
          name: new Date().valueOf()
        }
        this.uploadImgToOss(raw, true)
          .then((response) => {
            this.form.valueData.avatar = response
            this.postersList = [{ url: response }]
            if (this.postersList.length > 0) {
              this.cancelValidate()
            }
            this.hideUpload = true
          })
          .finally(() => {
            this.cropper.dialog = false
          })
      })
    },
    // 提交
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (this.postersList.length > 0) {
          this.cancelValidate()
        }
        if (valid) {
          // alert("submit!");
          console.log('成功提交')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancelValidate() {
      this.$refs['posters'].clearValidate()
      this.rules.posters[0].required = false
    }
  }
}
</script>

<style lang='scss' scoped>
#contentBox {
  padding: 10px 20px;
}
/deep/ .el-form-item__error {
  left: 77px;
}
/deep/ .el-dialog__footer {
  text-align: right;
}
/deep/ .el-dialog__footer > .footer {
  text-align: right !important;
}
.hide /deep/.el-upload--picture-card {
  display: none;
  width: 100px;
  height: 100px;
}
</style>
